package com.minutes.in.seconds.ui.screens;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract.Calendars;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

import com.minutes.in.seconds.MisApp;
import com.minutes.in.seconds.R;
import com.minutes.in.seconds.common.Constants;
import com.minutes.in.seconds.entity.Person;
import com.minutes.in.seconds.utils.MisUtils;
import com.reptilemobile.MultipleContactsPicker.ContactData;

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

	List<Person> attendees = new ArrayList<Person>();

	List<Person> speakers = new ArrayList<Person>();

	// Projection array. Creating indices for this array instead of doing
	// dynamic lookups improves performance.
	public static final String[] EVENT_PROJECTION = new String[] { Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME, Calendars.ACCOUNT_NAME, Calendars.OWNER_ACCOUNT };

	// The indices for the projection array above.
	private static final int PROJECTION_ID_INDEX = 0;
	private static final int PROJECTION_DISPLAY_NAME_INDEX = 1;
	private static final int PROJECTION_ACCOUNT_NAME_INDEX = 2;
	private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();

		MenuBarFragment menuBarFragment = new MenuBarFragment();
		MisApp.menuBar = menuBarFragment;
		transaction.replace(R.id.menubarLayout, menuBarFragment, Constants.MENU_BAR);

		LibraryActivity libraryActivity = new LibraryActivity();
		transaction.replace(R.id.fragment, libraryActivity, Constants.SCREEN_LIBRARY);

		getLoaderManager().initLoader(0, null, this);

		// Commit the transaction
		transaction.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// Run query
		String primaryEmail = MisUtils.getEmail(this);
		Uri uri = Calendars.CONTENT_URI;

		String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?) AND (" + Calendars.OWNER_ACCOUNT + " = ?))";
		String[] selectionArgs = new String[] { primaryEmail, "com.google", primaryEmail };

		return new CursorLoader(this, uri, EVENT_PROJECTION, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cur) {
		// Use the cursor to step through the returned records
		while (cur.moveToNext()) {
			// Get the field values
			long calID = cur.getLong(PROJECTION_ID_INDEX);
			String displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
			String accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
			String ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);

			MisApp.calendarId = calID;
		}

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1001 || requestCode == 1002) {
			if (resultCode == Activity.RESULT_OK) {
				if (data.hasExtra(ContactData.CONTACTS_DATA)) {
					ArrayList<ContactData> contacts = data.getParcelableArrayListExtra(ContactData.CONTACTS_DATA);

					if (contacts != null) {

						Iterator<ContactData> iterContacts = contacts.iterator();
						while (iterContacts.hasNext()) {

							ContactData contact = iterContacts.next();

							Person person = new Person();
							person.setEmail(contact.email);
							person.setMobileNumber(contact.phoneNmb);
							person.setName(contact.firstname);
							person.setSurName(contact.lastname);

							if (requestCode == 1001) {
								speakers.add(person);
							} else {
								attendees.add(person);
							}

						}

						FragmentManager fragmentManager = getSupportFragmentManager();
						AddMeetingActivity addMeetingActivity = (AddMeetingActivity) fragmentManager.findFragmentByTag(Constants.SCREEN_ADD_MEETING);
						if (addMeetingActivity != null) {
							if (requestCode == 1001) {
								addMeetingActivity.getSpeakerCount().setText(String.valueOf(speakers.size()));
							} else {
								addMeetingActivity.getAttendeeCount().setText(String.valueOf(attendees.size()));
							}
						}
					}
				}
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * @return the attendees
	 */
	public List<Person> getAttendees() {
		return attendees;
	}

	/**
	 * @return the speakers
	 */
	public List<Person> getSpeakers() {
		return speakers;
	}
}
